package space.panker916.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import space.panker916.dao.CommentMapper;
import space.panker916.pojo.Comment;
import space.panker916.utils.SensitiveFilter;

import java.util.List;

import static space.panker916.utils.Constants.ENTITY_TYPE_POST;


@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    // 设置事务默认的 隔离级别 和 传播机制 （默认的是啥？？？）
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        // 处理一下评论的内容
        comment.setContent(sensitiveFilter.filter(HtmlUtils.htmlEscape(comment.getContent())));

        // 添加评论
        int rows = commentMapper.insertComment(comment);

        // 如果是 发的是帖子评论，更新帖子评论的数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.selectCountByEntity(ENTITY_TYPE_POST, comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }

        return rows;
    }
}
